package com.zadtek.shopmall.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.AddressItem;
import com.zadtek.shopmall.bean.PayModeItem;
import com.zadtek.shopmall.bean.RedItem;
import com.zadtek.shopmall.bean.SubmitOrderBean;
import com.zadtek.shopmall.bean.SubmitOrderProductItem;
import com.zadtek.shopmall.bean.SubmitOrderShopItem;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.dialog.BaseNiceDialog;
import com.zadtek.shopmall.view.dialog.NiceDialog;
import com.zadtek.shopmall.view.dialog.ViewConvertListener;
import com.zadtek.shopmall.view.dialog.ViewHolder;

import java.util.LinkedList;
import java.util.List;

public class SubmitOrderActivity extends AbsActivity implements View.OnClickListener {
    private TextView tvNamePhone;
    private TextView tvAddress;
    private ImageView ivAddress;
    private LinearLayout llShopContainer;
    private TextView tvPayMode;
    private TextView tvInvoice;
    private TextView tvRedEnvelopNum;
    private TextView tvRedEnvelop;
    private TextView tvIntegral;
    private Switch swIntegral;
    private TextView tvBuyPrice;
    private TextView tvUseRedEnvelop;
    private TextView tvRealPay;
    private TextView tvBtnSubmit;
    private ImageView ivBack;
    private TextView title;
    private SubmitOrderBean orderBean;
    private LinearLayout llRedContainer;

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.ic_back);
        ivBack.setVisibility(View.VISIBLE);
        title = (TextView)findViewById(R.id.title);
        title.setText("提交订单");
        tvNamePhone = (TextView)findViewById( R.id.tv_name_phone );
        tvAddress = (TextView)findViewById( R.id.tv_address );
        ivAddress = (ImageView)findViewById( R.id.iv_address );
        llShopContainer = (LinearLayout)findViewById( R.id.ll_shop_container );
        tvPayMode = (TextView)findViewById( R.id.tv_pay_mode );
        tvInvoice = (TextView)findViewById( R.id.tv_invoice );
        tvRedEnvelopNum = (TextView)findViewById( R.id.tv_red_envelop_num );
        tvRedEnvelop = (TextView)findViewById( R.id.tv_red_envelop );
        tvIntegral = (TextView)findViewById( R.id.tv_integral );
        swIntegral = (Switch)findViewById( R.id.sw_integral );
        tvBuyPrice = (TextView)findViewById( R.id.tv_buy_price );
        tvUseRedEnvelop = (TextView)findViewById( R.id.tv_use_red_envelop );
        tvRealPay = (TextView)findViewById( R.id.tv_real_pay );
        tvBtnSubmit = (TextView)findViewById( R.id.tv_btn_submit );
        llRedContainer = (LinearLayout) findViewById(R.id.ll_red_container);
    }

    @Override
    public int setView() {
        return R.layout.activity_submit_order;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        initLogic();
        requestData();
    }

    private void requestData() {
        orderBean = new SubmitOrderBean();
        AddressItem addressItem = new AddressItem();
        addressItem.setPhone("15680487267");
        addressItem.setName("zackdk");
        addressItem.setAddressDetail("四川省龙泉驿区十陵成都大学");
        orderBean.setAddressItem(addressItem);
        orderBean.setInvoiceInfo("个人不需要发票");
        List<RedItem> redItems = new LinkedList<>();
        RedItem redItem = new RedItem();
        redItem.setMoney(100);
        redItem.setReason("全场满1000减100");
        redItem.setTimeString("2018.1.1~2018.4.4");
        RedItem redItem2 = new RedItem();
        redItem2.setMoney(100);
        redItem2.setReason("全场满1000减100");
        redItem2.setTimeString("2018.1.1~2018.4.4");
        redItems.add(redItem);
        redItems.add(redItem2);
        orderBean.setRedItems(redItems);

        SubmitOrderShopItem shopItem = new SubmitOrderShopItem();
        shopItem.setShopname("旗舰店");
        shopItem.setDeliverMode("韵达快递");
        shopItem.setTotalNum(4);
        List<SubmitOrderProductItem> productList = new LinkedList<>();
        SubmitOrderProductItem item = new SubmitOrderProductItem();
        item.setBuyNum(1);
        item.setProductPrice(99);
        item.setProductTitle("东方航空说的话说服客户的三款发动机是");
        productList.add(item);
        productList.add(item);
        productList.add(item);
        productList.add(item);
        shopItem.setProductItems(productList);

        List<SubmitOrderShopItem> shopItemList = new LinkedList<>();

        shopItemList.add(shopItem);
        shopItemList.add(shopItem);
        orderBean.setShopItems(shopItemList);
        Gson gson = new Gson();
        String json = gson.toJson(orderBean);
        updateView();
    }

    private void updateView() {
        tvNamePhone.setText(orderBean.getAddressItem().getName()+"    "+orderBean.getAddressItem().getPhone());
        tvAddress.setText(orderBean.getAddressItem().getAddressDetail());
        int payMode = orderBean.getPayMode();
        if(payMode == 0){
            tvPayMode.setText("支付宝");
        }else if(payMode == 1){
            tvPayMode.setText("微信");
        }
        tvInvoice.setText(orderBean.getInvoiceInfo());
        tvRedEnvelopNum.setText("红包（"+orderBean.getRedItems().size()+"张)");
        tvRedEnvelop.setText("未使用红包");
        tvUseRedEnvelop.setText("未使用红包");
        tvIntegral.setText(String.valueOf(orderBean.getIntergral()));

        updateShopView(orderBean.getShopItems());
        cacluatePrice();
    }

    private void cacluatePrice() {
        float totalPrice = 0;
        for(SubmitOrderShopItem shopItem:orderBean.getShopItems()){
            totalPrice+=shopItem.getTotalPrice();
        }
        orderBean.setProductTotalPrice(totalPrice);
        tvBuyPrice.setText("￥"+orderBean.getProductTotalPrice());
        float reduction = 0;
        for(RedItem redItem:orderBean.getRedItems()){
            if(redItem.isSelected()){
                reduction += redItem.getMoney();
            }
        }
        if(reduction == 0){
            tvRedEnvelop.setText("未使用红包");
            llRedContainer.setVisibility(View.GONE);

        }else{
            tvRedEnvelop.setText("优惠金额 ￥"+reduction);
            llRedContainer.setVisibility(View.VISIBLE);
            tvUseRedEnvelop.setText("-￥"+reduction);
        }
        float real = totalPrice - reduction;
        tvRealPay.setText("￥"+real);
    }

    private void updateShopView(List<SubmitOrderShopItem> shopItemList) {
        for(int i = 0;i<shopItemList.size();i++){
            final SubmitOrderShopItem shopItem = shopItemList.get(i);
            View v = getLayoutInflater().inflate(R.layout.submitorder_item,null);
            TextView shopName = (TextView) v.findViewById(R.id.tv_shop_name);
            TextView totalProductNum = (TextView) v.findViewById(R.id.tv_total_product);
            TextView deliverMode = (TextView) v.findViewById(R.id.tv_deliver_mode);
            LinearLayout container = (LinearLayout) v.findViewById(R.id.ll_product_container);
            EditText etMessage = (EditText)v.findViewById(R.id.et_buyer_message);

            etMessage.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    shopItem.setBuyerMessage(editable.toString());
                }
            });
            shopName.setText(shopItem.getShopname());
            deliverMode.setText(shopItem.getDeliverMode());
            float totalPrice = 0;
            for(SubmitOrderProductItem productItem:shopItem.getProductItems()){
                totalPrice+=productItem.getProductPrice();
            }
            shopItem.setTotalPrice(totalPrice);
            totalProductNum.setText("共"+shopItem.getTotalNum()+"件商品    合计：￥"+shopItem.getTotalPrice());
            updateProductList(shopItem.getProductItems(),container,i);
            llShopContainer.addView(v);
        }
    }

    private void updateProductList(List<SubmitOrderProductItem> productItems, LinearLayout container, final int shopPosition) {
        for(int i =0;i<productItems.size();i++){
            SubmitOrderProductItem item = productItems.get(i);
            View v = getLayoutInflater().inflate(R.layout.submit_product_item,null);
            ImageView img = (ImageView) v.findViewById(R.id.iv_product_img);
            TextView price = (TextView) v.findViewById(R.id.tv_product_price);
            TextView title = (TextView) v.findViewById(R.id.tv_product_title);
            TextView num = (TextView) v.findViewById(R.id.tv_product_num);
            price.setText(String.valueOf(item.getProductPrice()));
            title.setText(item.getProductTitle());
            num.setText("x "+item.getBuyNum());
            final int finalI = i;
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtil.showToast("shopPosition:"+shopPosition+" productPosition:"+ finalI);
                }
            });
            container.addView(v);
        }
    }


    private void initLogic() {
        tvPayMode.setOnClickListener(this);
        tvInvoice.setOnClickListener(this);
        tvRedEnvelop.setOnClickListener(this);
        tvBtnSubmit.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        ivAddress.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_address:
                ToastUtil.showToast("选择地址界面！");
                startActivity(new Intent(this,ChooseAddressActivity.class));
                break;
            case R.id.tv_pay_mode:
                ToastUtil.showToast("选择支付方式！");
                pickPayMode();
                break;
            case R.id.tv_invoice:
                ToastUtil.showToast("选择发票信息！");
                break;
            case R.id.tv_red_envelop:
                ToastUtil.showToast("选择使用的红包！");
                pickRedEnvelop();
                break;
            case R.id.tv_btn_submit:
                ToastUtil.showToast("提交订单请求！");
                startActivity(new Intent(this, OrderActivity.class));
                finish();
                break;
            case R.id.ic_back:
                finish();
                break;
        }

    }

    private void pickRedEnvelop() {
        final List<RedItem> redItems = orderBean.getRedItems();
        final NiceDialog dialog = NiceDialog.init();
        dialog.setLayoutId(R.layout.base_choose_layout)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    protected void convertView(ViewHolder viewHolder, BaseNiceDialog baseNiceDialog) {
                        RecyclerView container = (RecyclerView) viewHolder.getView(R.id.recycleview);
                        ImageView close = (ImageView) viewHolder.getView(R.id.iv_close);
                        close.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        LinearLayoutManager layoutManager = new LinearLayoutManager(SubmitOrderActivity.this);
                        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                        container.setLayoutManager(layoutManager);
                        chooseRedEnvelopAdapter adapter = new chooseRedEnvelopAdapter(R.layout.red_envelop_item,redItems);
//                        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                            @Override
//                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                                redItems.get(position).setSelected(true);
//                                cacluatePrice();
//                                dialog.dismiss();
//                            }
//                        });
                        container.setAdapter(adapter);
                    }
                })
                .setShowBottom(true);
        dialog.show(getSupportFragmentManager());
    }

    private void pickPayMode() {
        final List<PayModeItem> payMode = new LinkedList<>();
        PayModeItem payModeItem = new PayModeItem();
        payModeItem.setCode(0);
        payModeItem.setName("支付宝支付");
        payModeItem.setSelected(false);
        PayModeItem payModeItem2 = new PayModeItem();
        payModeItem2.setCode(1);
        payModeItem2.setName("微信支付");
        payModeItem2.setSelected(false);
        PayModeItem payModeItem3 = new PayModeItem();
        payModeItem3.setCode(2);
        payModeItem3.setName("余额支付");
        payModeItem3.setSelected(false);
        PayModeItem payModeItem4 = new PayModeItem();
        payModeItem4.setCode(3);
        payModeItem4.setName("货到付款");
        payModeItem4.setSelected(false);


        payMode.add(payModeItem);
        payMode.add(payModeItem2);
        payMode.add(payModeItem3);
        payMode.add(payModeItem4);
        for(PayModeItem item:payMode){
            if(item.getCode() == orderBean.getPayMode()){
                item.setSelected(true);
            }
        }
        final NiceDialog dialog = NiceDialog.init();
                dialog.setLayoutId(R.layout.base_choose_layout)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    protected void convertView(ViewHolder viewHolder, BaseNiceDialog baseNiceDialog) {
                        RecyclerView container = (RecyclerView) viewHolder.getView(R.id.recycleview);
                        ImageView close = (ImageView) viewHolder.getView(R.id.iv_close);
                        close.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        LinearLayoutManager layoutManager = new LinearLayoutManager(SubmitOrderActivity.this);
                        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                        container.setLayoutManager(layoutManager);
                        chooseAdapter adapter = new chooseAdapter(R.layout.pay_mode_item,payMode);
                        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                for(PayModeItem item:payMode){
                                    item.setSelected(false);
                                }
                                payMode.get(position).setSelected(true);
                                orderBean.setPayMode(payMode.get(position).getCode());
                                tvPayMode.setText(payMode.get(position).getName());
                                dialog.dismiss();
                            }
                        });
                        container.setAdapter(adapter);
                    }
                })
                .setShowBottom(true);
        dialog.show(getSupportFragmentManager());
    }

    private class chooseAdapter extends BaseQuickAdapter<PayModeItem,BaseViewHolder>{

        public chooseAdapter(int layoutResId, @Nullable List<PayModeItem> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, PayModeItem item) {
            helper.setText(R.id.tv_pay_name,item.getName());
            helper.setVisible(R.id.iv_choose,item.isSelected());
        }
    }
    private class chooseRedEnvelopAdapter extends BaseQuickAdapter<RedItem,BaseViewHolder>{

        public chooseRedEnvelopAdapter(int layoutResId, @Nullable List<RedItem> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final RedItem item) {
            //helper.setText(R.id.tv_pay_name,item.getName());
            //helper.setVisible(R.id.iv_choose,item.isSelected());
            helper.setVisible(R.id.checkbox,true);
            helper.setChecked(R.id.checkbox,item.isSelected());
            helper.setOnCheckedChangeListener(R.id.checkbox, new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    item.setSelected(b);
                    cacluatePrice();
                }
            });
        }
    }

}
